package com.example.pan.ui.file

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import com.example.pan.R
import com.example.pan.databinding.ItemFileInfoBinding
import com.example.pan.model.FileInfo
import com.example.pan.ui.base.BaseViewHolder
import com.example.pan.ui.formatBit
import com.example.pan.ui.formatDate

class ListFileInfoAdapter :
    PagingDataAdapter<FileInfo, BaseViewHolder<ItemFileInfoBinding>>(callback) {

    private var itemClickListener: OnItemClickListener? = null


    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): BaseViewHolder<ItemFileInfoBinding> {
        val binding =
            ItemFileInfoBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return BaseViewHolder(binding)
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: BaseViewHolder<ItemFileInfoBinding>, position: Int) {
        val item = getItem(position)
        item?.let {
            val binding = holder.binding
            binding.fileName.text = it.server_filename
            var simpleInfo = formatDate(it.local_mtime)
            if (it.isdir == 1) {
                binding.icon.setImageResource(R.drawable.ic_folder_black_24dp)
            } else {
                binding.icon.setImageResource(getFileIcon(it.category))
                simpleInfo += " ${formatBit(it.size)}"
            }
            binding.simpleInfo.text = simpleInfo
            binding.fileSelect.setOnClickListener {
                itemClickListener?.onMoreFunClick(item, binding.fileSelect)
            }
            holder.itemView.setOnClickListener {
                itemClickListener?.onItemClick(item)
            }
        }
    }

    private fun getFileIcon(category: Int): Int = when (category) {
        1 -> R.drawable.ic_video_black_24dp
        2 -> R.drawable.ic_music_black_24dp
        3 -> R.drawable.ic_photo_black_24dp
        4 -> R.drawable.ic_text_black_24dp
        else -> R.drawable.ic_file_black_24dp
    }


    interface OnItemClickListener {
        fun onItemClick(item: FileInfo)

        fun onMoreFunClick(item: FileInfo, view: View)

        fun onBackClick()
    }

    fun setOnItemClickListener(listener: OnItemClickListener) {
        this.itemClickListener = listener
    }

    companion object {
        private val callback = object : DiffUtil.ItemCallback<FileInfo>() {
            override fun areItemsTheSame(oldItem: FileInfo, newItem: FileInfo): Boolean {
                return oldItem.fs_id == newItem.fs_id
            }

            override fun areContentsTheSame(oldItem: FileInfo, newItem: FileInfo): Boolean {
                return oldItem == newItem
            }

        }
    }
}